package com.block.datapush.service.apipush;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.JuYouHuaUtil;
import com.block.datapush.service.apipush.utils.KaKaHuaQiUtil;
import com.block.datapush.service.apipush.utils.QiDaiAesUtil;
import com.block.db.entity.ApplicationInfo;
import com.block.db.entity.MemberSourceInfo;
import com.block.db.entity.MerchantBaseInfo;
import com.block.db.entity.MerchantDataPushInfo;
import com.block.db.mapper.MerchantBaseInfoMapper;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 96 卡卡花  回调
 */
@Service
public class KakahuaPushApiService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();

    @Autowired
    IMemberCommonService memberCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;
    @Resource
    MerchantBaseInfoMapper merchantBaseInfoMapper;
    @Resource
    MerchantDataPushInfoMapper merchantDataPushInfoMapper;


    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String queryUrl = pushApiKeyParam.getCheckUrl();

        String mobileMd5 = memberSourceInfo.getMobileMd5();
        long timestamp = System.currentTimeMillis();

        Map<String, Object> Map = new HashMap<>();
        Map.put("loadAmount", KaKaHuaQiUtil.getloan(memberSourceInfo.getLoanAmount()));
        Map.put("zhima", KaKaHuaQiUtil.getZhimaScore(memberSourceInfo.getZhima()));
        Map.put("house", KaKaHuaQiUtil.getHouse(memberSourceInfo.getHouse()));
        Map.put("car", KaKaHuaQiUtil.getCar(memberSourceInfo.getCar()));
        Map.put("pubFund", KaKaHuaQiUtil.getGjj(memberSourceInfo.getGjj()));
        Map.put("guarantor", KaKaHuaQiUtil.getbaodan(memberSourceInfo.getBaoxian()));
        Map.put("businessLicense", KaKaHuaQiUtil.getjob1(memberSourceInfo.getGongzuo()));
        Map.put("creditRecord", KaKaHuaQiUtil.getYuqi(memberSourceInfo.getYuqi()));
        Map.put("creditCard", 1);
        Map.put("socialSecurity", KaKaHuaQiUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        Map.put("weilidai", 1);
        Map.put("term", KaKaHuaQiUtil.getloanTime(memberSourceInfo.getLoanTime()));
        Map.put("baitiao", KaKaHuaQiUtil.getBaitiao(memberSourceInfo.getBaitiao()));
        Map.put("industry", KaKaHuaQiUtil.getjob(memberSourceInfo.getGongzuo()));
        Map.put("monthIncome", KaKaHuaQiUtil.getshouru(memberSourceInfo.getShouru()));
        Map.put("salaryType", 1);

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("version", "1.0.0");
        bizMap.put("timestamp", timestamp);
        bizMap.put("mobile", mobileMd5);
        bizMap.put("username", memberSourceInfo.getRealname());
        bizMap.put("idCard", memberSourceInfo.getIdcard());
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("sex", memberSourceInfo.getSex());
        bizMap.put("city", memberSourceInfo.getCity());
        bizMap.put("mobilePlatform", "android");
        bizMap.put("ip", memberSourceInfo.getReqIp());
        bizMap.put("fieldInfo", JSON.toJSONString(Map));

        String content = SecureUtil.aes(pushApiKeyParam.getApiKey().getBytes()).encryptBase64(JSON.toJSONString(bizMap));

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("accountNo", pushApiKeyParam.getApiCode());
        paramMap.put("data", content);

        log.info("【卡卡花】撞库开始【queryUrl】{}【paramMap】{}【bizMap】{}", queryUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【卡卡花】撞库结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String errMsg = resultObject.getString("errMsg");

        JSONObject data = resultObject.getJSONObject("data");

        pushApiResult.setCode(code + "|");
        pushApiResult.setMessage(errMsg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            pushApiResult.setPushSuccess(true);
        }
        return pushApiResult;
    }

    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);

        String requestUrl = pushApiKeyParam.getRegisterUrl();

        long timestamp = System.currentTimeMillis();

        Map<String, Object> Map = new HashMap<>();
        Map.put("loadAmount", KaKaHuaQiUtil.getloan(memberSourceInfo.getLoanAmount()));
        Map.put("zhima", KaKaHuaQiUtil.getZhimaScore(memberSourceInfo.getZhima()));
        Map.put("house", KaKaHuaQiUtil.getHouse(memberSourceInfo.getHouse()));
        Map.put("car", KaKaHuaQiUtil.getCar(memberSourceInfo.getCar()));
        Map.put("pubFund", KaKaHuaQiUtil.getGjj(memberSourceInfo.getGjj()));
        Map.put("guarantor", KaKaHuaQiUtil.getbaodan(memberSourceInfo.getBaoxian()));
        Map.put("businessLicense", KaKaHuaQiUtil.getjob1(memberSourceInfo.getGongzuo()));
        Map.put("creditRecord", KaKaHuaQiUtil.getYuqi(memberSourceInfo.getYuqi()));
        Map.put("creditCard", 1);
        Map.put("socialSecurity", KaKaHuaQiUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        Map.put("weilidai", 1);
        Map.put("term", KaKaHuaQiUtil.getloanTime(memberSourceInfo.getLoanTime()));
        Map.put("baitiao", KaKaHuaQiUtil.getBaitiao(memberSourceInfo.getBaitiao()));
        Map.put("industry", KaKaHuaQiUtil.getjob(memberSourceInfo.getGongzuo()));
        Map.put("monthIncome", KaKaHuaQiUtil.getshouru(memberSourceInfo.getShouru()));
        Map.put("salaryType", 1);

        Map<String, Object> bizMap = new HashMap<>();
        bizMap.put("version", "1.0.0");
        bizMap.put("serialNo", orderNo);
        bizMap.put("timestamp", timestamp);
        bizMap.put("mobile", memberSourceInfo.getMobile());
        bizMap.put("username", memberSourceInfo.getRealname());
        bizMap.put("idCard", memberSourceInfo.getIdcard());
        bizMap.put("age", memberSourceInfo.getAge());
        bizMap.put("sex", memberSourceInfo.getSex());
        bizMap.put("city", memberSourceInfo.getCity());
        bizMap.put("mobilePlatform", "android");
        bizMap.put("ip", memberSourceInfo.getReqIp());
        bizMap.put("fieldInfo", JSON.toJSONString(Map));

        ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(memberSourceInfo.getAppCode());
        String jumpUrl = StrUtil.format("{}prodList", appInfoByAppCode.getH5Url(), memberSourceInfo.getChannelCode());

        bizMap.put("redirectUrl", jumpUrl);

        String content = SecureUtil.aes(pushApiKeyParam.getApiKey().getBytes()).encryptBase64(JSON.toJSONString(bizMap));

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("accountNo", pushApiKeyParam.getApiCode());
        paramMap.put("data", content);


        log.info("【卡卡花】导单开始【queryUrl】{}【paramMap】{}【bizMap】{}", requestUrl, JSON.toJSONString(paramMap), JSON.toJSONString(bizMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
        log.info("【卡卡花】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String errMsg = resultObject.getString("errMsg");
        JSONObject data = resultObject.getJSONObject("data");

        pushApiResult.setCode(code + "|");
        pushApiResult.setMessage(errMsg);
        pushApiResult.setParamInfo(JSON.toJSONString(bizMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {

            String url = data.getString("url");
            pushApiResult.setApproveUrl(url);
            pushApiResult.setOutOrderNo(orderNo);

            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(false);
            pushApiResult.setStatus(PushStatusEnum.WAIT_APPROVE.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) throws Exception {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();

        JSONObject jsonObject = JSON.parseObject(paramContent);
        String data = jsonObject.getString("data");

        MerchantBaseInfo merchantBaseInfo = merchantBaseInfoMapper.selectById(infoId);

        String dataStr = SecureUtil.aes(merchantBaseInfo.getApiKey().getBytes()).decryptStr(data);
        log.info("【卡卡花】回调通知参数【dataStr】{}", dataStr);

        JSONObject dataObject = JSON.parseObject(dataStr);
        String serialNo = dataObject.getString("serialNo");

        noticeParamDTO.setOutOrderNo(serialNo);
        noticeParamDTO.setOutFlag(true);
        noticeParamDTO.setQueryResult(paramContent);

        MerchantDataPushInfo entityByOutOrderNoLock = merchantDataPushInfoMapper.getEntityByOutOrderNoLock(infoId, String.valueOf(serialNo));
        noticeParamDTO.setMerchantDataPushInfo(entityByOutOrderNoLock);

        noticeParamDTO.setSettleFlag(true);
        noticeParamDTO.setStatus(PushStatusEnum.SUCCESS.getValue());

        return noticeParamDTO;
    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 200);
        jsonObject.put("msg", "成功");
        return jsonObject;
    }

    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        return null;
    }

    public static void main(String[] args) {

        String content = "MbYPQUwh0UbFwoG+VhDX\\/S5PWME+1cPKIKX+d9xefnSEebOGdSgvleCuMwD2W8ax";

        String dataStr = SecureUtil.aes("CB613DE5A22EDBA9".getBytes()).decryptStr(content);

        System.out.println(dataStr);
    }


}
